<template>
  <div class="mod-user">
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :option="tableOption"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @on-load="getDataList"
    >
      <template slot="menuLeft">
        <el-button type="primary" @click="dialogVisible4 = true" size="small"
          >导入用户积分</el-button
        >
        <el-button type="primary" @click="dialogVisible5 = true" size="small"
          >导入用户优惠券</el-button
        >
        <el-button type="info" @click="derive(0)" size="small"
          >导出全部</el-button
        >
        <el-button
          type="danger"
          @click="deleteHandle()"
          v-if="isAuth('admin:user:delete')"
          size="small"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
        <input
          type="file"
          id="wuliuid"
          @change="importf(this)"
          style="display:none;"
        />
      </template>

      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status === 0" size="mini" type="danger"
          >禁用</el-tag
        >
        <el-tag v-else size="mini">正常</el-tag>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-dropdown style="height:33px;">
          <el-button style="height:33px;" type="success" size="small"
            >积分</el-button
          >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-button
                type="warning"
                icon="el-icon-check"
                size="small"
                @click.stop="addintegral(scope.row.userId)"
                >下发积分</el-button
              >
            </el-dropdown-item>
            <el-dropdown-item>
              <el-button
                type="success"
                icon="el-icon-edit"
                size="small"
                @click.stop="integrallist(scope.row.userId)"
                >积分记录</el-button
              >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown style="height:33px;">
          <el-button style="height:33px;" type="warning" size="small"
            >优惠券</el-button
          >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-button
                type="danger"
                icon="el-icon-star-off"
                size="small"
                @click.stop="addcoupon(scope.row.userId)"
                >下发优惠券</el-button
              >
            </el-dropdown-item>
            <el-dropdown-item>
              <el-button
                type="info"
                icon="el-icon-message"
                size="small"
                @click.stop="couponlist(scope.row.userId)"
                >优惠券记录</el-button
              >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-button
          type="primary"
          icon="el-icon-edit"
          size="small"
          v-if="isAuth('admin:user:update')"
          @click.stop="addOrUpdateHandle(scope.row.userId)"
          >编辑</el-button
        >

        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          v-if="isAuth('admin:user:delete')"
          @click.stop="deleteHandle(scope.row.userId)"
          >删除</el-button
        >
      </template>
    </avue-crud>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>

    <el-dialog title="积分记录" :visible.sync="dialogVisible3" width="30%">
      <div class="demo-input-suffix" style="overflow:auto;height:300px;">
        <div class="integralcon" v-for="(value, ind) in integralli" :key="ind">
          <div class="tit">
            <div class="left">日期:{{ value.createTime }}</div>
            <div :class="value.type == 1 ? 'red' : 'green'">
              类型:{{ value.type == 1 ? "支出" : "收入" }}
            </div>
          </div>
          <div class="con">
            <div class="left">积分数量:</div>
            <div class="right">{{ value.amount }}</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="derive(1)" size="small"
          >导出用户积分</el-button
        >
        <el-button type="primary" @click="dialogVisible3 = false" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- <el-dialog title="下发优惠券" :visible.sync="dialogVisible1" width="30%">
      这个不能用了,因为统一优惠券,后续不统一,这个可以用
      <div class="demo-input-suffix" style="margin:20px 0;">
        <label>优惠券类型:</label>
        <el-select v-model="coupon.couponId" style="width:350px;" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.couponName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submityouhui(),dialogVisible1 = false">确定</el-button>
      </span>
    </el-dialog>-->

    <el-dialog title="下发优惠券" :visible.sync="dialogVisible1" width="30%">
      <div class="demo-input-suffix" style="margin:20px 0;">
        <label>优惠券数量:</label>
        <el-input v-model="coupon.couponCount" style="width:300px;"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submityouhui(), (dialogVisible1 = false)"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="下发优惠券记录"
      :visible.sync="dialogVisible2"
      width="30%"
    >
      <div class="demo-input-suffix" style="overflow:auto;height:300px;">
        <div class="couponcon" v-for="(value, ind) in couponli" :key="ind">
          <div class="tit">
            <div class="left">数量:{{ value.count }}</div>
            <div class="left">{{ value.mark }}</div>
          </div>
          <div class="tit">
            <div class="left">日期:{{ value.createTime }}</div>
            <div :class="value.type == 1 ? 'green' : 'red'">
              类型:{{ value.type == 1 ? "发放" : "使用" }}
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="derive(2)" size="small"
          >导出用户优惠券</el-button
        >
        <el-button type="primary" @click="dialogVisible2 = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="导入用户积分" :visible.sync="dialogVisible4" width="30%">
      <div class="demo-input-suffix" style="margin:20px 0;">
        <el-image src="../../../../config/images/pic002.png"></el-image>
      </div>
      <div class="demo-input-suffix">
        <el-button @click="getwuliuinfo()" type="primary" size="small"
          >导入用户积分表格</el-button
        >
        <label v-show="filename != null">{{ filename }}</label>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button
          type="primary"
          @click="fullscreenLoading=true"
          v-loading.fullscreen.lock="fullscreenLoading"
        >指令方式</el-button>-->

        <el-button
          type="primary"
          @click="(dialogVisible6 = true), importlist(1)"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="导入用户优惠券"
      :visible.sync="dialogVisible5"
      width="30%"
    >
      <div class="demo-input-suffix" style="margin:20px 0;">
        <el-image src="../../../../config/images/pic003.png"></el-image>
      </div>
      <div class="demo-input-suffix">
        <el-button @click="getwuliuinfo()" type="primary" size="small"
          >导入用户优惠券表格</el-button
        >
        <label v-show="filename != null">{{ filename }}</label>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="(dialogVisible6 = true), importlist(2)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title :visible.sync="dialogVisible6" width="30%">
      <div>操作执行中,请稍等</div>
    </el-dialog>
  </div>
</template>

<script>
import { tableOption } from "@/crud/user/user";
import AddOrUpdate from "./user-add-or-update";
export default {
  data() {
    return {
      filename: null,
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      dialogVisible4: false,
      dialogVisible5: false,
      dialogVisible6: false,
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      tableOption: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      options: [],
      integralli: [
        {
          id: 0,
          name: null
        }
      ],
      coupon: {
        couponCount: null,
        uid: null
      },
      couponli: [],
      importli: [],
      fullscreenLoading: false,
      userid: ""
    };
  },
  components: {
    AddOrUpdate
  },
  methods: {
    // 获取数据列表
    getDataList(page, params) {
      this.dataListLoading = true;
      // console.log(params);
      // console.log(page);

      this.$http({
        url: this.$http.adornUrl("/admin/user/page"),
        method: "get",
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize
            },
            params
          )
        )
      }).then(({ data }) => {
        this.dataList = data.records;
        this.page.total = data.total;
        this.dataListLoading = false;
      });
    },
    addcoupon(id) {
      console.log(id);
      this.dialogVisible1 = true;
      this.coupon.uid = id;
      this.$http({
        url: this.$http.adornUrl("/admin/coupon/page"),
        method: "GET"
      }).then(({ data }) => {
        this.options = data;
      });
    },
    addintegral(id) {
      console.log(id);

      this.$prompt("请输入积分", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          var data = {
            amount: value,
            mark: "",
            type: 2,
            userId: id
          };
          this.$http({
            url: this.$http.adornUrl("/admin/score"),
            method: "put",
            data: data
          }).then(({ data }) => {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList(this.page);
              }
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    integrallist(id) {
      this.dialogVisible3 = true;
      this.userid = id;
      this.$http({
        url: this.$http.adornUrl("/admin/score?userId=" + id),
        method: "GET"
      }).then(({ data }) => {
        this.integralli = data;
      });
    },
    couponlist(id) {
      this.dialogVisible2 = true;
      this.userid = id;
      this.$http({
        url: this.$http.adornUrl("/admin/coupon/history?uid=" + id),
        method: "GET"
      }).then(({ data }) => {
        this.couponli = data;
      });
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.userId;
          });
      this.$confirm(`确定进行[${id ? "删除" : "批量删除"}]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/admin/user"),
            method: "delete",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList(this.page);
              }
            });
          });
        })
        .catch(() => {});
    },
    // 条件查询
    searchChange(params) {
      this.getDataList(this.page, params);
    },
    // 多选变化
    selectionChange(val) {
      this.dataListSelections = val;
    },
    submityouhui() {
      this.coupon.couponCount = parseInt(this.coupon.couponCount);
      this.$http({
        url: this.$http.adornUrl(
          "/admin/coupon/send?uid=" +
            this.coupon.uid +
            "&couponCount=" +
            this.coupon.couponCount
        ),
        method: "post",
        data: this.coupon
      }).then(({ data }) => {
        this.coupon = {
          couponCount: null,
          uid: null
        };
      });
    },
    getwuliuinfo() {
      let inpfile = document.getElementById("wuliuid").click();
    },
    importf() {
      /*
     FileReader共有4种读取方法：
     1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
     2.readAsBinaryString(file)：将文件读取为二进制字符串
     3.readAsDataURL(file)：将文件读取为Data URL
     4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
     */
      let that = this;
      var obj = document.getElementById("wuliuid");
      console.log(obj);
      this.filename = obj.files[0].name;
      //导入
      if (!obj.files) {
        return;
      }
      var f = obj.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        var data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            //手动转化
            type: "base64"
          });
        } else {
          wb = XLSX.read(data, {
            type: "binary"
          });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        console.log(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));

        that.importli = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      };
      var wb; //读取完成的数据
      var rABS = false; //是否将文件读取为二进制字符串

      function fixdata(data) {
        //文件流转BinaryString
        var o = "",
          l = 0,
          w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(
            null,
            new Uint8Array(data.slice(l * w, l * w + w))
          );
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
      }
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    importlist(i) {
      let that = this;
      let arr = [];
      this.filename = "";
      switch (i) {
        case 1:
          for (let i = 0; i < that.importli.length; i++) {
            if (!that.importli[i]["员工工号"]) {
              this.$message.error("找不到员工工号列, 或数据格式错误");
              setTimeout(() => {
                window.location.reload();
              }, 500);
              return false;
            }

            if (!that.importli[i]["积分值"]) {
              this.$message.error("找不到积分值列, 或数据格式错误");
              setTimeout(() => {
                window.location.reload();
              }, 500);
              return false;
            }

            let da = {
              score: that.importli[i]["积分值"].replace("积分", "").trim(),
              userCode: that.importli[i]["员工工号"].trim()
            };
            arr.push(da);
          }

          that
            .$http({
              url: that.$http.adornUrl("/admin/score/import"),
              method: "post",
              data: arr
            })
            .then(({ data }) => {
              this.$message({
                message: "积分导入成功",
                type: "success"
              });
              setTimeout(() => {
                window.location.reload();
              }, 200);
            })
            .catch(err => {
              console.log(err);
            });

          break;
        case 2:
          for (let i = 0; i < that.importli.length; i++) {
            if (!that.importli[i]["员工工号"]) {
              this.$message.error("找不到员工工号列, 或数据格式错误");
              setTimeout(() => {
                window.location.reload();
              }, 500);
              return false;
            }

            if (!that.importli[i]["5%折扣券（张数）"]) {
              this.$message.error("找不到5%折扣券（张数）列, 或数据格式错误");
              setTimeout(() => {
                window.location.reload();
              }, 500);
              return false;
            }

            let da = {
              count: that.importli[i]["5%折扣券（张数）"],
              userCode: that.importli[i]["员工工号"]
            };

            arr.push(da);
          }

          that
            .$http({
              url: that.$http.adornUrl("/admin/coupon/import"),
              method: "post",
              data: arr
            })
            .then(({ data }) => {
              this.$message({
                message: "优惠券导入成功",
                type: "success"
              });
              window.location.reload();
            });

          that.dialogVisible6 = false;
          that.dialogVisible5 = false;

          break;
        case 3:
          break;

        default:
          break;
      }
    },
    derive(ind) {
      console.log("导出");
      var that = this;
      var str = "";
      var blob;
      switch (ind) {
        case 0:
          that
            .$http({
              url: that.$http.adornUrl("/output/all"),
              method: "get"
            })
            .then(({ data }) => {
              for (let i = 0; i < data.length; i++) {
                for (let key in data[i]) {
                  str += data[i][key] + "\t";
                }
                str += "\n";
              }
              callback(str, "全部用户记录");
            });
          break;
        case 1:
          that
            .$http({
              url: that.$http.adornUrl("/output/score/" + this.userid),
              method: "get"
            })
            .then(({ data }) => {
              for (let i = 0; i < data.length; i++) {
                for (let key in data[i]) {
                  str += data[i][key] + "\t";
                }
                str += "\n";
              }
              callback(str, "个人积分记录");
            });
          break;
        case 2:
          that
            .$http({
              url: that.$http.adornUrl("/output/coupon/" + this.userid),
              method: "get"
            })
            .then(({ data }) => {
              for (let i = 0; i < data.length; i++) {
                for (let key in data[i]) {
                  str += data[i][key] + "\t";
                }
                str += "\n";
              }
              callback(str, "个人优惠券记录");
            });
          break;

        default:
          break;
      }

      function callback(data, txt) {
        var blob = new Blob([data], {
          type:
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
          //"application/octet-stream"
        });
        const fileName = txt + ".xls";
        const elink = document.createElement("a");
        elink.href = URL.createObjectURL(blob);
        if ("download" in elink) {
          // 非IE下载
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      }
    }
  },
  mounted() {
    // this.$http({
    //   url: this.$http.adornUrl("/admin/coupon/page"),
    //   method: "get",
    //   params: this.$http.adornParams()
    // }).then(({ data }) => {});
  }
};
</script>
<style>
.integralcon {
  display: flex;
  flex-direction: column;
  height: 70px;
  line-height: 70px;
  padding: 5px;
  border-bottom: solid 1px #f9f9f9;
}
.integralcon .tit {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  line-height: 30px;
}
.integralcon .tit .red {
  color: #ff0000;
}
.integralcon .tit .green {
  color: #00ff00;
}
.integralcon .con {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  height: 30px;
  line-height: 30px;
}
.integralcon .con .right {
  font-weight: 600;
  font-size: 18px;
}

.couponcon {
  display: flex;
  flex-direction: column;
  height: 70px;
  line-height: 70px;
  padding: 5px;
  border-bottom: solid 1px #f9f9f9;
}
.couponcon .tit {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  line-height: 30px;
}
.couponcon .tit .red {
  color: #ff0000;
}
.couponcon .tit .green {
  color: #00ff00;
}
.couponcon .tit .gray {
  color: #909399;
}
</style>
